import pymysql
# from flask import current_app
from settings import Config


class SQLHelper(object):
    @staticmethod
    def open(cursor):
        # conn = pymysql.connect(host='localhost',
        #                        port=3306, password='qaz3357375', user='root',
        #                        db='test')
        # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        # POOL = current_app.config['PYMYSQL_POOL']
        POOL = Config.PYMYSQL_POOL
        conn = POOL.connection()
        cursor = conn.cursor(cursor=cursor)
        return conn, cursor

    @staticmethod
    def close(conn, cursor):
        conn.commit()
        cursor.close()
        conn.close()

    @classmethod
    def fetch_one(cls, sql, args, cursor=pymysql.cursors.DictCursor):
        conn, cursor = cls.open(cursor)
        cursor.execute(sql, args)
        obj = cursor.fetchone()
        cls.close(conn, cursor)
        return obj

    @classmethod
    def fetch_all(cls, sql, args, cursor=pymysql.cursors.DictCursor):
        conn, cursor = cls.open(cursor)
        cursor.execute(sql, args)
        obj = cursor.fetchall()
        cls.close(conn, cursor)
        return obj
